package com.ruoyi.pingan.fymodule.separateSetting.categorytemplate.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ruoyi.pingan.exception.CommonException;
import com.ruoyi.pingan.fymodule.separateSetting.categorytemplate.entity.FywCategoryTemplate;
import com.ruoyi.pingan.fymodule.separateSetting.categorytemplate.entity.FywCategoryTemplateDto;
import com.ruoyi.pingan.fymodule.separateSetting.categorytemplate.mapper.FywCategoryTemplateMapper;
import com.ruoyi.pingan.fymodule.separateSetting.categorytemplate.param.FywCategoryTemplateAddParam;
import com.ruoyi.pingan.fymodule.separateSetting.categorytemplate.param.FywCategoryTemplateEditParam;
import com.ruoyi.pingan.fymodule.separateSetting.categorytemplate.param.FywCategoryTemplateIdParam;
import com.ruoyi.pingan.fymodule.separateSetting.categorytemplate.param.FywCategoryTemplatePageParam;
import com.ruoyi.pingan.fymodule.separateSetting.categorytemplate.service.FywCategoryTemplateService;
import com.ruoyi.pingan.fymodule.separateSetting.storesetting.entity.FywGoodsCategory;
import com.ruoyi.pingan.fymodule.separateSetting.storesetting.entity.FywStoreSetting;
import com.ruoyi.pingan.fymodule.separateSetting.storesetting.service.FywGoodsCategoryService;
import com.ruoyi.pingan.fymodule.separateSetting.storesetting.service.FywStoreSettingService;
import com.ruoyi.pingan.util.CommonDownloadUtil;
import com.ruoyi.pingan.util.CommonResponseUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 分账品类模板表Service接口实现类
 *
 * @author zjf
 * @date  2025/07/29 15:14
 **/
@Service
public class FywCategoryTemplateServiceImpl extends ServiceImpl<FywCategoryTemplateMapper, FywCategoryTemplate> implements FywCategoryTemplateService {


    @Autowired
    private FywGoodsCategoryService fywGoodsCategoryService;

    @Autowired
    private FywStoreSettingService fywStoreSettingService;

    private static final Random random = new Random();
    private static final Set<Integer> generatedIds = new HashSet<>();

    @Override
    public Page<FywCategoryTemplateDto> page(FywCategoryTemplatePageParam fywCategoryTemplatePageParam) {

        Page<FywCategoryTemplateDto> page = new Page<>();

            List<FywCategoryTemplate>       lists = this.list();
            List<FywCategoryTemplateDto> resultLists = new ArrayList<>();
            boolean defaultFlag = true;
            for(FywCategoryTemplate fywCategoryTemplate:lists){
                List<Map<String, Object>>  typeList = new ArrayList<>();
                if(fywCategoryTemplate.getIsDefault().equals("1")){
                    defaultFlag = false;
                }
                FywCategoryTemplateDto fywCategoryTemplateDto = new FywCategoryTemplateDto();
                fywCategoryTemplateDto.setCategoryId(fywCategoryTemplate.getCategoryId());
                QueryWrapper<FywGoodsCategory> queryWrapper = new QueryWrapper<FywGoodsCategory>().checkSqlInjection();
                queryWrapper.lambda().eq(FywGoodsCategory::getCategoryId, fywCategoryTemplate.getCategoryId());

                FywGoodsCategory fywGoodsCategory = fywGoodsCategoryService.getOne(queryWrapper);
                if(fywGoodsCategory!=null&&fywGoodsCategory.getId()!=null){
                    HashMap<String,Object> map =  new HashMap<>();
                    map.put("label","药品");
                    map.put("value",fywGoodsCategory.getYpSettleRate());
                    typeList.add(map);
                    HashMap<String,Object> spmap =  new HashMap<>();
                    spmap.put("label","食品");
                    spmap.put("value",fywGoodsCategory.getSpSettleRate());
                    typeList.add(spmap);
                    HashMap<String,Object> ylqxmap =  new HashMap<>();
                    ylqxmap.put("label","医疗器械");
                    ylqxmap.put("value",fywGoodsCategory.getYlqxSettleRate());
                    typeList.add(ylqxmap);
                    HashMap<String,Object> rypmap =  new HashMap<>();
                    rypmap.put("label","日用品");
                    rypmap.put("value",fywGoodsCategory.getRypSettleRate());
                    typeList.add(rypmap);
                    HashMap<String,Object> hzpmap =  new HashMap<>();
                    hzpmap.put("label","化妆品");
                    hzpmap.put("value",fywGoodsCategory.getHzpSettleRate());
                    typeList.add(hzpmap);
                    HashMap<String,Object> bjypmap =  new HashMap<>();
                    bjypmap.put("label","保健用品");
                    bjypmap.put("value",fywGoodsCategory.getBjypSettleRate());
                    typeList.add(bjypmap);
                    HashMap<String,Object> zyypmap =  new HashMap<>();
                    zyypmap.put("label","中药饮品");
                    zyypmap.put("value",fywGoodsCategory.getZyypSettleRate());
                    typeList.add(zyypmap);
                }else{
                    HashMap<String,Object> map =  new HashMap<>();

                    map.put("label","药品");
                    map.put("value","");
                    typeList.add(map);
                    HashMap<String,Object> spmap =  new HashMap<>();
                    spmap.put("label","食品");
                    spmap.put("value","");
                    typeList.add(spmap);
                    HashMap<String,Object> ylqxmap =  new HashMap<>();
                    ylqxmap.put("label","医疗器械");
                    ylqxmap.put("value","");
                    typeList.add(ylqxmap);
                    HashMap<String,Object> rypmap =  new HashMap<>();
                    rypmap.put("label","日用品");
                    rypmap.put("value","");
                    typeList.add(rypmap);
                    HashMap<String,Object> hzpmap =  new HashMap<>();
                    hzpmap.put("label","化妆品");
                    hzpmap.put("value","");
                    typeList.add(hzpmap);
                    HashMap<String,Object> bjypmap =  new HashMap<>();
                    bjypmap.put("label","保健用品");
                    bjypmap.put("value","");
                    typeList.add(bjypmap);
                    HashMap<String,Object> zyypmap =  new HashMap<>();
                    zyypmap.put("label","中药饮品");
                    zyypmap.put("value","");
                    typeList.add(zyypmap);
                }

                fywCategoryTemplateDto.setCategoryName(fywCategoryTemplate.getCategoryName());
                fywCategoryTemplateDto.setId(fywCategoryTemplate.getId());
                fywCategoryTemplateDto.setIsDefault(fywCategoryTemplate.getIsDefault());

                QueryWrapper<FywStoreSetting> storeNumWrapper = new QueryWrapper<FywStoreSetting>().checkSqlInjection();
                storeNumWrapper.select("DISTINCT store_id");
                storeNumWrapper.lambda().eq(FywStoreSetting::getCategoryId, fywCategoryTemplate.getId());
                List<FywStoreSetting> storeNums =  fywStoreSettingService.list(storeNumWrapper);
                fywCategoryTemplateDto.setStoreNum(storeNums.size()==0 ?"0":String.valueOf(storeNums.size()));
                fywCategoryTemplateDto.setTypeList(typeList);
                resultLists.add(fywCategoryTemplateDto);
            }
            if(defaultFlag){
                resultLists.get(0).setIsDefault("1");

            }

            page.setRecords(resultLists);
            page.setTotal(resultLists.size());



     return page;


    }

    @Override
    public FywCategoryTemplateDto newCategory(FywCategoryTemplateAddParam fywCategoryTemplateAddParam) {
        FywCategoryTemplateDto fresult = new FywCategoryTemplateDto();
        List<Map<String, Object>>  typeList = new ArrayList<>();
        HashMap<String,Object> map =  new HashMap<>();

        map.put("label","药品");
        map.put("value","");
        typeList.add(map);
        HashMap<String,Object> spmap =  new HashMap<>();
        spmap.put("label","食品");
        spmap.put("value","");
        typeList.add(spmap);
        HashMap<String,Object> ylqxmap =  new HashMap<>();
        ylqxmap.put("label","医疗器械");
        ylqxmap.put("value","");
        typeList.add(ylqxmap);
        HashMap<String,Object> rypmap =  new HashMap<>();
        rypmap.put("label","日用品");
        rypmap.put("value","");
        typeList.add(rypmap);
        HashMap<String,Object> hzpmap =  new HashMap<>();
        hzpmap.put("label","化妆品");
        hzpmap.put("value","");
        typeList.add(hzpmap);
        HashMap<String,Object> bjypmap =  new HashMap<>();
        bjypmap.put("label","保健用品");
        bjypmap.put("value","");
        typeList.add(bjypmap);
        HashMap<String,Object> zyypmap =  new HashMap<>();
        zyypmap.put("label","中药饮品");
        zyypmap.put("value","");
        typeList.add(zyypmap);
        fresult.setTypeList(typeList);
        return fresult;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(FywCategoryTemplateAddParam fywCategoryTemplateAddParam) {

        if (ObjectUtil.isNotEmpty(fywCategoryTemplateAddParam.getId())) {
           //编辑
            FywCategoryTemplate fywCategoryTemplate = new FywCategoryTemplate();
            fywCategoryTemplate.setId(fywCategoryTemplateAddParam.getId());
            fywCategoryTemplate.setCategoryId(fywCategoryTemplateAddParam.getCategoryId());
            fywCategoryTemplate.setCategoryName(fywCategoryTemplateAddParam.getCategoryName());
            fywCategoryTemplate.setIsDefault(fywCategoryTemplateAddParam.getIsDefault());
            fywCategoryTemplate.setStoreNum(fywCategoryTemplateAddParam.getStoreNum());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date date =new Date();
            fywCategoryTemplate.setUpdTime(sdf.format(date));
            this.updateById(fywCategoryTemplate);

            List<Map<String, Object>> typeList = fywCategoryTemplateAddParam.getTypeList();

            FywGoodsCategory fywGoodsCategory = new FywGoodsCategory();

            List<Map<String, Object>> transformedList = typeList.stream()
                    .map(map -> {
                        Map<String, Object> newMap = new HashMap<>();
                        newMap.put(map.get("label").toString(), map.get("value"));
                        return newMap;
                    })
                    .collect(Collectors.toList());
            for (int i = 0; i < transformedList.size(); i++) {

                Map<String, Object> map = transformedList.get(i);
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    System.out.println("Index: " + i + ", Key: " + entry.getKey() + ", Value: " + entry.getValue());
                    if(entry.getKey().equals("药品")){
                        fywGoodsCategory.setYpSettleRate(getBigDecimal(entry.getValue()));
                    }
                    if(entry.getKey().equals("食品")){
                        fywGoodsCategory.setSpSettleRate(getBigDecimal(entry.getValue()));
                    }
                    if(entry.getKey().equals("医疗器械")){
                        fywGoodsCategory.setYlqxSettleRate(getBigDecimal(entry.getValue()));
                    }
                    if(entry.getKey().equals("日用品")){
                        fywGoodsCategory.setRypSettleRate(getBigDecimal(entry.getValue()));
                    }
                    if(entry.getKey().equals("化妆品")){
                        fywGoodsCategory.setHzpSettleRate(getBigDecimal(entry.getValue()));
                    }
                    if(entry.getKey().equals("保健用品")){
                        fywGoodsCategory.setBjypSettleRate(getBigDecimal(entry.getValue()));
                    }
                    if(entry.getKey().equals("中药饮品")){
                        fywGoodsCategory.setZyypSettleRate(getBigDecimal(entry.getValue()));
                    }

                }

            }
            fywGoodsCategory.setCategoryId(fywCategoryTemplateAddParam.getCategoryId());
            fywGoodsCategoryService.updateById(fywGoodsCategory);


        }else{
            //新增
            FywCategoryTemplate fywCategoryTemplateAdd = new FywCategoryTemplate();
            String categoryId = generateUniqueId();
            fywCategoryTemplateAdd.setCategoryId(categoryId);
            fywCategoryTemplateAdd.setCategoryName(fywCategoryTemplateAddParam.getCategoryName());
            //先判断是否有存在默认模板，如果没有取1，有默认取0
            boolean isdefaultFlag = false;
            List<FywCategoryTemplate> templateList = this.list();
            if(templateList.size()>0){
                for(FywCategoryTemplate fywCategoryTemplate:templateList){

                    if(fywCategoryTemplate.getIsDefault().equals("1")){

                        isdefaultFlag = true;
                        break;
                    }

                }

            }

            if(isdefaultFlag){
                fywCategoryTemplateAdd.setIsDefault("0");


            }else{
                fywCategoryTemplateAdd.setIsDefault("1");

            }
            fywCategoryTemplateAdd.setStoreNum(fywCategoryTemplateAddParam.getStoreNum());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date date =new Date();
            fywCategoryTemplateAdd.setUpdTime(sdf.format(date));
            this.save(fywCategoryTemplateAdd);
            List<Map<String, Object>> typeList = fywCategoryTemplateAddParam.getTypeList();

            FywGoodsCategory fywGoodsCategory = new FywGoodsCategory();

            List<Map<String, Object>> transformedList = typeList.stream()
                    .map(map -> {
                        Map<String, Object> newMap = new HashMap<>();
                        newMap.put(map.get("label").toString(), map.get("value"));
                        return newMap;
                    })
                    .collect(Collectors.toList());
            for (int i = 0; i < transformedList.size(); i++) {

                Map<String, Object> map = transformedList.get(i);
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    System.out.println("Index: " + i + ", Key: " + entry.getKey() + ", Value: " + entry.getValue());
                    if(entry.getKey().equals("药品")){
                        fywGoodsCategory.setYpSettleRate(getBigDecimal(entry.getValue()));
                    }
                    if(entry.getKey().equals("食品")){
                        fywGoodsCategory.setSpSettleRate(getBigDecimal(entry.getValue()));
                    }
                    if(entry.getKey().equals("医疗器械")){
                        fywGoodsCategory.setYlqxSettleRate(getBigDecimal(entry.getValue()));
                    }
                    if(entry.getKey().equals("日用品")){
                        fywGoodsCategory.setRypSettleRate(getBigDecimal(entry.getValue()));
                    }
                    if(entry.getKey().equals("化妆品")){
                        fywGoodsCategory.setHzpSettleRate(getBigDecimal(entry.getValue()));
                    }
                    if(entry.getKey().equals("保健用品")){
                        fywGoodsCategory.setBjypSettleRate(getBigDecimal(entry.getValue()));
                    }
                    if(entry.getKey().equals("中药饮品")){
                        fywGoodsCategory.setZyypSettleRate(getBigDecimal(entry.getValue()));
                    }

                }

            }
            fywGoodsCategory.setCategoryId(categoryId);
            fywGoodsCategoryService.save(fywGoodsCategory);

        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(FywCategoryTemplateEditParam fywCategoryTemplateEditParam) {
        FywCategoryTemplate fywCategoryTemplate = this.queryEntity(fywCategoryTemplateEditParam.getId());
        BeanUtil.copyProperties(fywCategoryTemplateEditParam, fywCategoryTemplate);
        this.updateById(fywCategoryTemplate);

        List<Map<String, Object>> typeList = fywCategoryTemplateEditParam.getTypeList();

        QueryWrapper<FywGoodsCategory> queryWrapper = new QueryWrapper<FywGoodsCategory>().checkSqlInjection();
        queryWrapper.lambda().eq(FywGoodsCategory::getCategoryId, fywCategoryTemplateEditParam.getCategoryId());

        FywGoodsCategory fywGoodsCategory = fywGoodsCategoryService.getOne(queryWrapper);

        List<Map<String, Object>> transformedList = typeList.stream()
                .map(map -> {
                    Map<String, Object> newMap = new HashMap<>();
                    newMap.put(map.get("label").toString(), map.get("value"));
                    return newMap;
                })
                .collect(Collectors.toList());
        for (int i = 0; i < transformedList.size(); i++) {

            Map<String, Object> map = transformedList.get(i);
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                System.out.println("Index: " + i + ", Key: " + entry.getKey() + ", Value: " + entry.getValue());
                if(entry.getKey().equals("药品")){
                    fywGoodsCategory.setYpSettleRate(getBigDecimal(entry.getValue()));
                }
                if(entry.getKey().equals("食品")){
                    fywGoodsCategory.setSpSettleRate(getBigDecimal(entry.getValue()));
                }
                if(entry.getKey().equals("医疗器械")){
                    fywGoodsCategory.setYlqxSettleRate(getBigDecimal(entry.getValue()));
                }
                if(entry.getKey().equals("日用品")){
                    fywGoodsCategory.setRypSettleRate(getBigDecimal(entry.getValue()));
                }
                if(entry.getKey().equals("化妆品")){
                    fywGoodsCategory.setHzpSettleRate(getBigDecimal(entry.getValue()));
                }
                if(entry.getKey().equals("保健用品")){
                    fywGoodsCategory.setBjypSettleRate(getBigDecimal(entry.getValue()));
                }
                if(entry.getKey().equals("中药饮品")){
                    fywGoodsCategory.setZyypSettleRate(getBigDecimal(entry.getValue()));
                }

            }

        }
        fywGoodsCategoryService.updateById(fywGoodsCategory);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(FywCategoryTemplateIdParam fywCategoryTemplateIdParam) {
        // 执行删除
        FywCategoryTemplate fywCategoryTemplate = this.getById(fywCategoryTemplateIdParam.getId());
        if(fywCategoryTemplate!=null){
            QueryWrapper<FywGoodsCategory> deleteWrapper = new QueryWrapper<FywGoodsCategory>().checkSqlInjection();
            deleteWrapper.lambda().eq(FywGoodsCategory::getCategoryId,fywCategoryTemplate.getCategoryId());
            fywGoodsCategoryService.remove(deleteWrapper);

        }
        this.removeById(fywCategoryTemplateIdParam.getId());


    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void defaultset(FywCategoryTemplateIdParam fywCategoryTemplateIdParam) {

        //获取categoryId 然后去表里查询 再把其他表里的状态默认值统一不是默认状态变更
        if(fywCategoryTemplateIdParam.getIsDefault().equals("1")){
            List<FywCategoryTemplate> defaultList = this.list();
            for(FywCategoryTemplate fywCategoryTemplate : defaultList){
                fywCategoryTemplate.setIsDefault("0");
            }
            this.updateBatchById(defaultList);

            for(FywCategoryTemplate fywCategoryTemplate : defaultList){
                if(fywCategoryTemplate.getId().equals(fywCategoryTemplateIdParam.getId())){

                    fywCategoryTemplate.setIsDefault(fywCategoryTemplateIdParam.getIsDefault());
                    this.updateById(fywCategoryTemplate);

                }

            }

        }else{
            List<FywCategoryTemplate> defaultList = this.list();
            for(FywCategoryTemplate fywCategoryTemplate : defaultList){
                if(fywCategoryTemplate.getId().equals(fywCategoryTemplateIdParam.getId())){
                    fywCategoryTemplate.setIsDefault(fywCategoryTemplateIdParam.getIsDefault());
                    this.updateById(fywCategoryTemplate);
                }
            }
        }


    }

    @Override
    public FywCategoryTemplate detail(FywCategoryTemplateIdParam fywCategoryTemplateIdParam) {
        return this.queryEntity(fywCategoryTemplateIdParam.getId());
    }



    @Override
    public void downloadImportTemplate(HttpServletResponse response) throws IOException {
       File tempFile = null;
       try {
         List<FywCategoryTemplateEditParam> dataList = CollectionUtil.newArrayList();
         String fileName = "分账品类模板表导入模板_" + DateUtil.format(DateTime.now(), DatePattern.PURE_DATETIME_PATTERN) + ".xlsx";
         tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);
         EasyExcel.write(tempFile.getPath(), FywCategoryTemplateEditParam.class).sheet("分账品类模板表").doWrite(dataList);
         CommonDownloadUtil.download(tempFile, response);
       } catch (Exception e) {
         log.error(">>> 分账品类模板表导入模板下载失败：", e);
         CommonResponseUtil.renderError(response, "分账品类模板表导入模板下载失败");
       } finally {
         FileUtil.del(tempFile);
       }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONObject importData(MultipartFile file) {
        try {
            int successCount = 0;
            int errorCount = 0;
            JSONArray errorDetail = JSONUtil.createArray();
            // 创建临时文件
            File tempFile = FileUtil.writeBytes(file.getBytes(), FileUtil.file(FileUtil.getTmpDir() +
                    FileUtil.FILE_SEPARATOR + "fywCategoryTemplateImportTemplate.xlsx"));
            // 读取excel
            List<FywCategoryTemplateEditParam> fywCategoryTemplateEditParamList =  EasyExcel.read(tempFile).head(FywCategoryTemplateEditParam.class).sheet()
                    .headRowNumber(1).doReadSync();
            List<FywCategoryTemplate> allDataList = this.list();
            for (int i = 0; i < fywCategoryTemplateEditParamList.size(); i++) {
                JSONObject jsonObject = this.doImport(allDataList, fywCategoryTemplateEditParamList.get(i), i);
                if(jsonObject.getBool("success")) {
                    successCount += 1;
                } else {
                    errorCount += 1;
                    errorDetail.add(jsonObject);
                }
            }
            return JSONUtil.createObj()
                    .set("totalCount", fywCategoryTemplateEditParamList.size())
                    .set("successCount", successCount)
                    .set("errorCount", errorCount)
                    .set("errorDetail", errorDetail);
        } catch (Exception e) {
            log.error(">>> 分账品类模板表导入失败：", e);
            throw new CommonException("分账品类模板表导入失败");
        }
    }

    public JSONObject doImport(List<FywCategoryTemplate> allDataList, FywCategoryTemplateEditParam fywCategoryTemplateEditParam, int i) {
        String id = fywCategoryTemplateEditParam.getId();
        if(ObjectUtil.hasEmpty(id)) {
            return JSONUtil.createObj().set("index", i + 1).set("success", false).set("msg", "必填字段存在空值");
        } else {
            try {
                int index = CollStreamUtil.toList(allDataList, FywCategoryTemplate::getId).indexOf(fywCategoryTemplateEditParam.getId());
                FywCategoryTemplate fywCategoryTemplate;
                boolean isAdd = false;
                if(index == -1) {
                    isAdd = true;
                    fywCategoryTemplate = new FywCategoryTemplate();
                } else {
                    fywCategoryTemplate = allDataList.get(index);
                }
                BeanUtil.copyProperties(fywCategoryTemplateEditParam, fywCategoryTemplate);
                if(isAdd) {
                    allDataList.add(fywCategoryTemplate);
                } else {
                    allDataList.remove(index);
                    allDataList.add(index, fywCategoryTemplate);
                }
                this.saveOrUpdate(fywCategoryTemplate);
                return JSONUtil.createObj().set("success", true);
            } catch (Exception e) {
              log.error(">>> 数据导入异常：", e);
              return JSONUtil.createObj().set("success", false).set("index", i + 1).set("msg", "数据导入异常");
            }
        }
    }

    @Override
    public FywCategoryTemplate queryEntity(String id) {
        FywCategoryTemplate fywCategoryTemplate = this.getById(id);
        if(ObjectUtil.isEmpty(fywCategoryTemplate)) {
            throw new CommonException("分账品类模板表不存在，id值为：{}", id);
        }
        return fywCategoryTemplate;
    }

    @Override
    public void exportData(List<FywCategoryTemplateIdParam> fywCategoryTemplateIdParamList, HttpServletResponse response) throws IOException {
       File tempFile = null;
       try {
         List<FywCategoryTemplateEditParam> dataList;
         if(ObjectUtil.isNotEmpty(fywCategoryTemplateIdParamList)) {
            List<String> idList = CollStreamUtil.toList(fywCategoryTemplateIdParamList, FywCategoryTemplateIdParam::getId);
            dataList = BeanUtil.copyToList(this.listByIds(idList), FywCategoryTemplateEditParam.class);
         } else {
            dataList = BeanUtil.copyToList(this.list(), FywCategoryTemplateEditParam.class);
         }
         String fileName = "分账品类模板表_" + DateUtil.format(DateTime.now(), DatePattern.PURE_DATETIME_PATTERN) + ".xlsx";
         tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);
         EasyExcel.write(tempFile.getPath(), FywCategoryTemplateEditParam.class).sheet("分账品类模板表").doWrite(dataList);
         CommonDownloadUtil.download(tempFile, response);
       } catch (Exception e) {
         log.error(">>> 分账品类模板表导出失败：", e);
         CommonResponseUtil.renderError(response, "分账品类模板表导出失败");
       } finally {
         FileUtil.del(tempFile);
       }
    }

    public static String generateUniqueId() {
        int id;
        do {
            id = random.nextInt(10000); // 生成0到9999之间的随机数
        } while (generatedIds.contains(id));

        generatedIds.add(id);
        return String.format("%04d", id); // 返回四位数字字符串
    }

    /**
     * Object转BigDecimal类型
     *
     * @param value 要转的object类型
     * @return 转成的BigDecimal类型数据
     */
    public static BigDecimal getBigDecimal(Object value) {
        BigDecimal ret = null;
        if (value != null) {
            if (value instanceof BigDecimal) {
                ret = (BigDecimal) value;
            } else if (value instanceof String) {
                ret = new BigDecimal((String) value);
            } else if (value instanceof BigInteger) {
                ret = new BigDecimal((BigInteger) value);
            } else if (value instanceof Number) {
                ret = new BigDecimal(((Number) value).doubleValue());
            } else {
                throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass() + " into a BigDecimal.");
            }
        }
        return ret;
    }



}
